package com.shadow.study.shiro.config;

import com.shadow.study.shiro.LoginUser;
import com.shadow.study.shiro.entity.ShiroPermissionEntity;
import com.shadow.study.shiro.entity.ShiroRoleEntity;
import com.shadow.study.shiro.entity.ShiroUserEntity;
import com.shadow.study.shiro.service.ShiroPermissionService;
import com.shadow.study.shiro.service.ShiroRoleService;
import com.shadow.study.shiro.service.ShiroUserService;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import javax.annotation.Resource;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

public class ShiroDbRealm extends AuthorizingRealm {

    @Resource
    private ShiroUserService shiroUserService;
    @Resource
    private ShiroRoleService shiroRoleService;
    @Resource
    private ShiroPermissionService shiroPermissionService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

    /**
     * 认证.
     * SecurityUtils.getSubject().login(token)
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String name = (String) token.getPrincipal();
        if (StringUtils.isBlank(name)) {
            ShiroUserEntity user = shiroUserService.selectByName(name);
            if (Objects.nonNull(user)) {
                Set<String> roles = shiroRoleService.selectByUserId(user.getId())
                        .stream()
                        .map(ShiroRoleEntity::getName)
                        .collect(Collectors.toSet());
                Set<String> permissions = shiroPermissionService.selectByUserId(user.getId())
                        .stream()
                        .map(ShiroPermissionEntity::getName)
                        .collect(Collectors.toSet());

                LoginUser loginUser = new LoginUser();
                loginUser.setUserId(user.getId())
                        .setName(user.getName())
                        .setRoles(roles)
                        .setPermissions(permissions);
                return new SimpleAuthenticationInfo(loginUser, user.getPassword(), getName());
            }
        }
        return null;
    }
}
